package com.company.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.company.project.common.aop.annotation.LogAnnotation;
import com.company.project.common.utils.Func;
import com.company.project.entity.*;
import com.company.project.mapper.SysDeptMapper;
import com.company.project.mapper.TSeatsMapper;
import com.company.project.service.DeptService;
import com.company.project.service.RoleService;
import com.company.project.service.UserService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.company.project.common.utils.DataResult;

import com.company.project.service.TWdkhService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 
 *
 * @author wenbin
 * @email *****@mail.com
 * @date 2023-11-09 18:03:05
 */
@Controller
@RequestMapping("/")
public class TWdkhController {
    @Autowired
    private TWdkhService tWdkhService;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private DeptService deptService;
    @Resource
    private UserService sysUserService;
    @Resource
    private RoleService roleService;
    @Resource
    private TSeatsMapper tSeatsMapper;
    @Resource
    private UserService userService;
    /**
    * 跳转到页面
    */
    @GetMapping("/index/tWdkh")
    public String tWdkh() {
        return "twdkh/list";
        }

    @GetMapping("/index/tWdkh/ycj")
    public String tWdkhYcj() {
        return "twdkh/list_ycj";
    }
    @GetMapping("/index/tWdkh/wdkhedit/{wdkhId}")
    public String wdkhedit(Model model, @PathVariable("wdkhId") String wdkhId) {
        model.addAttribute("wdkhId",wdkhId);
        return "twdkh/wdkheidt";
    }
    @GetMapping("/index/tWdkh/add")
    public String wdkhadd() {
        return "twdkh/add";
    }
    @GetMapping("/index/tWdkh/now")
    public String tWdkhNow() {
        return "twdkh/list_now";
    }
    @ApiOperation(value = "新增")
    @PostMapping("tWdkh/add")
    @LogAnnotation(title = "我的客户", action = "新增")

//    @RequiresPermissions("tWdkh:add")
    @ResponseBody
    public DataResult add(@RequestBody TWdkhEntity tWdkh){
        return tWdkhService.add(tWdkh);
    }
    @ApiOperation(value = "新增")
    @PostMapping("index/tWdkh/add")
    @LogAnnotation(title = "我的客户", action = "index新增")
//    @RequiresPermissions("tWdkh:add")
    @ResponseBody
    public DataResult indexAdd(@RequestBody TWdkhEntity tWdkh){
        return tWdkhService.add(tWdkh);
    }
    @ApiOperation(value = "删除")
    @LogAnnotation(title = "我的客户", action = "删除")

    @DeleteMapping("tWdkh/delete")
    @RequiresPermissions("tWdkh:delete")
    @ResponseBody
    public DataResult delete(@RequestBody @ApiParam(value = "id集合") List<String> ids){
        tWdkhService.removeByIds(ids);
        return DataResult.success();
    }
    @ApiOperation(value = "扔入公海")
    @LogAnnotation(title = "我的客户", action = "扔入公海")

    @PostMapping("tWdkh/rlgh")
    @ResponseBody
    public DataResult rlgh(@RequestBody @ApiParam(value = "id集合与公海id") Map<String,Object> map){
        return tWdkhService.rlgh(map);
    }
    @ApiOperation(value = "更新")
    @LogAnnotation(title = "我的客户", action = "更新")

    @PutMapping("tWdkh/update")
    @ResponseBody
    public DataResult update(@RequestBody TWdkhEntity tWdkh){
        tWdkhService.updateById(tWdkh);
        return DataResult.success();
    }
    @ApiOperation(value = "查询分页数据")
    @LogAnnotation(title = "我的客户", action = "查询分页数据")

    @PostMapping("tWdkh/listByPage")
    @ResponseBody
    public DataResult findListByPage(@RequestBody TWdkhEntity tWdkh){
        return getPage(tWdkh,"0");
    }
    @ApiOperation(value = "查询 已成交 分页数据")
    @LogAnnotation(title = "我的客户", action = "查询 已成交 分页数据")

    @PostMapping("tWdkh/listByPage/ycj")
    @ResponseBody
    public DataResult findListByPageycj(@RequestBody TWdkhEntity tWdkh) {
        return getPage(tWdkh,"1");
    }
    private DataResult getPage(TWdkhEntity tWdkh ,String type) {
        Page page = new Page(tWdkh.getPage(), tWdkh.getLimit());
        LambdaQueryWrapper<TWdkhEntity> queryWrapper = Wrappers.lambdaQuery();
        //是否成交
        if (Func.equals("1",type)) {
            queryWrapper.eq(TWdkhEntity::getIscj, "1");
        } else {
            queryWrapper.eq(TWdkhEntity::getIscj, "0");
        }
        //公司名称--客户名称
        if (Func.isNotBlank(tWdkh.getKhname())) {
            queryWrapper.like(TWdkhEntity::getKhname, tWdkh.getKhname());
        }
        //联系人
        if (Func.isNotBlank(tWdkh.getLxr())) {
            queryWrapper.like(TWdkhEntity::getLxr, tWdkh.getLxr());
        }
        //联系电话
        if (Func.isNotBlank(tWdkh.getLxdh())) {
            queryWrapper.like(TWdkhEntity::getLxdh, tWdkh.getLxdh());
        }
        //所属销售
        if (Func.isNotBlank(tWdkh.getSsxs())) {
            queryWrapper.eq(TWdkhEntity::getSsxs, tWdkh.getSsxs());
        }
        //意向度---客户级别
        if (Func.isNotBlank(tWdkh.getKhjb())) {
            queryWrapper.eq(TWdkhEntity::getKhjb, tWdkh.getKhjb());
        }
        //客户来源
        if (Func.isNotBlank(tWdkh.getKhly())) {
            queryWrapper.eq(TWdkhEntity::getKhly, tWdkh.getKhly());
        }
        Calendar calendar = Calendar.getInstance();
        //最后跟进时间
        if (Func.isNotEmpty(tWdkh.getZhgjStartDate())) {
            calendar.setTime(tWdkh.getZhgjEndDate());
            calendar.add(Calendar.DAY_OF_MONTH,1);
            queryWrapper.between(TWdkhEntity::getZhgjtime, tWdkh.getZhgjStartDate(),calendar.getTime());
        }

        //下次联系时间
        if (Func.isNotEmpty(tWdkh.getXclxStartDate())) {
            calendar.setTime(tWdkh.getXclxEndDate());
            calendar.add(Calendar.DAY_OF_MONTH,1);
            queryWrapper.between(TWdkhEntity::getXclxtime, tWdkh.getXclxStartDate(),calendar.getTime());
        }

        //入库时间
        if (Func.isNotEmpty(tWdkh.getRkStartDate())) {
            calendar.setTime(tWdkh.getRkEndDate());
            calendar.add(Calendar.DAY_OF_MONTH,1);
            queryWrapper.between(TWdkhEntity::getRktime, tWdkh.getRkStartDate(),calendar.getTime());
        }
        //流公海时间
        if (Func.isNotEmpty(tWdkh.getLrghStartDate())) {
            calendar.setTime(tWdkh.getLrghEndDate());
            calendar.add(Calendar.DAY_OF_MONTH,1);
            queryWrapper.between(TWdkhEntity::getLrghtime, tWdkh.getLrghStartDate(),calendar.getTime());
        }
        SysUser userInfo = sysUserService.getUserInfo();
        //角色
        List<SysRole> roleInfoByUserId = roleService.getRoleInfoByUserId(userInfo.getId());
        List<String> collect = roleInfoByUserId.stream().map(e -> e.getName()).collect(Collectors.toList());

        //部门查询
        if (Func.isNotEmpty(tWdkh.getDept())) {
            SysDept sysDept = sysDeptMapper.selectOne(Wrappers.<SysDept>lambdaQuery()
                    .eq(SysDept::getId, tWdkh.getDept()));

            List<Object> deptIds = deptService.listObjs(Wrappers.<SysDept>lambdaQuery()
                    .select(SysDept::getId)
                    .like(SysDept::getRelationCode, sysDept.getDeptNo()));
            List<Object> usernames = sysUserService.listObjs(Wrappers.<SysUser>lambdaQuery().select(SysUser::getUsername).in(SysUser::getDeptId, deptIds));

            if (collect.contains("员工")){
                queryWrapper.eq(TWdkhEntity::getSsxs, userInfo.getUsername());
            } else {
                queryWrapper.in(TWdkhEntity::getSsxs, usernames);
            }
        } else {
            SysDept sysDept = sysDeptMapper.selectOne(Wrappers.<SysDept>lambdaQuery()
                    .eq(SysDept::getId, userInfo.getDeptId()));

            List<Object> deptIds = deptService.listObjs(Wrappers.<SysDept>lambdaQuery()
                    .select(SysDept::getId)
                    .like(SysDept::getRelationCode, sysDept.getDeptNo()));
            List<Object> usernames = sysUserService.listObjs(Wrappers.<SysUser>lambdaQuery().select(SysUser::getUsername).in(SysUser::getDeptId, deptIds));

            if (collect.contains("员工")){
                queryWrapper.eq(TWdkhEntity::getSsxs, userInfo.getUsername());
            } else {
                queryWrapper.in(TWdkhEntity::getSsxs, usernames);
            }
        }

        queryWrapper.eq(TWdkhEntity::getIsrlgh, "1");
        queryWrapper.orderByDesc(TWdkhEntity::getId);
        //查询条件示例 isrlgh
        //queryWrapper.eq(TWdkhEntity::getId, tWdkh.getId());
        IPage<TWdkhEntity> iPage = tWdkhService.page(page, queryWrapper);
        return DataResult.success(iPage);
    }

    @ApiOperation(value = "查询 今日待跟进客户 分页数据")
    @LogAnnotation(title = "我的客户", action = "查询 今日待跟进客户 分页数据")

    @PostMapping("tWdkh/listByPage/now")
//    @RequiresPermissions("tWdkh:list")
    @ResponseBody
    public DataResult findListByPageNow(@RequestBody TWdkhEntity tWdkh){
        Page page = new Page(tWdkh.getPage(), tWdkh.getLimit());
        LambdaQueryWrapper<TWdkhEntity> queryWrapper = Wrappers.lambdaQuery();
        //公司名称
        if (Func.isNotBlank(tWdkh.getCompany())) {
            queryWrapper.eq(TWdkhEntity::getCompany, tWdkh.getCompany());
        }
        //联系人
        if (Func.isNotBlank(tWdkh.getLxr())) {
            queryWrapper.eq(TWdkhEntity::getLxr, tWdkh.getLxr());
        }
        //联系电话
        if (Func.isNotBlank(tWdkh.getLxdh())) {
            queryWrapper.eq(TWdkhEntity::getLxdh, tWdkh.getLxdh());
        }
        //所属销售
        if (Func.isNotBlank(tWdkh.getSsxs())) {
            queryWrapper.eq(TWdkhEntity::getSsxs, tWdkh.getSsxs());
        }
        //客户来源
        if (Func.isNotBlank(tWdkh.getKhly())) {
            queryWrapper.eq(TWdkhEntity::getKhly, tWdkh.getKhly());
        }
        Calendar calendar = Calendar.getInstance();
        //最后跟进时间
        if (Func.isNotEmpty(tWdkh.getZhgjStartDate())) {
            calendar.setTime(tWdkh.getZhgjEndDate());
            calendar.add(Calendar.DAY_OF_MONTH,1);
            queryWrapper.between(TWdkhEntity::getZhgjtime, tWdkh.getZhgjStartDate(),calendar.getTime());
        }
        //入库时间
        if (Func.isNotEmpty(tWdkh.getRkStartDate())) {
            calendar.setTime(tWdkh.getRkEndDate());
            calendar.add(Calendar.DAY_OF_MONTH,1);
            queryWrapper.between(TWdkhEntity::getRktime, tWdkh.getRkStartDate(),calendar.getTime());
        }
        //流公海时间
        if (Func.isNotEmpty(tWdkh.getLrghStartDate())) {
            calendar.setTime(tWdkh.getLrghEndDate());
            calendar.add(Calendar.DAY_OF_MONTH,1);
            queryWrapper.between(TWdkhEntity::getLrghtime, tWdkh.getLrghStartDate(),calendar.getTime());
        }
        queryWrapper.eq(TWdkhEntity::getIsrlgh, "1");
        queryWrapper.orderByDesc(TWdkhEntity::getKhname);
        queryWrapper.orderByDesc(TWdkhEntity::getRktime);
        //查询条件示例
        IPage<TWdkhEntity> iPage = tWdkhService.page(page, queryWrapper);
        return DataResult.success(iPage);
    }
    @ApiOperation(value = "查询客户查重分页数据")
    @LogAnnotation(title = "我的客户", action = "查询客户查重分页数据")

    @PostMapping("tWdkh/khcc/listByPage")
//    @RequiresPermissions("tWdkh:list")
    @ResponseBody
    public DataResult khccFindListByPage(@RequestBody TWdkhEntity tWdkh){
        Page page = new Page(tWdkh.getPage(), tWdkh.getLimit());
        LambdaQueryWrapper<TWdkhEntity> queryWrapper = Wrappers.lambdaQuery();
        //查询条件示例
        String khname = tWdkh.getKhname();
        String lxdh = tWdkh.getLxdh();
        if (Func.isEmpty(khname)&&Func.isEmpty(lxdh)) {
            page.setSize(0);
        }
        IPage<TWdkhEntity> iPage = tWdkhService.pageKhcc(page, tWdkh);
        return DataResult.success(iPage);
    }

    @ApiOperation(value = "转移")
    @LogAnnotation(title = "我的客户", action = "转移")

    @PostMapping("tWdkh/zhuanyi")
//    @RequiresPermissions("tWdkh:add")
    @ResponseBody
    public DataResult zhuanyi(@RequestBody TWdkhEntity tWdkh){
        return tWdkhService.zhuanyi(tWdkh);
    }
   @ApiOperation(value = "领取")
   @LogAnnotation(title = "我的客户", action = "领取")
   @PostMapping("tWdkh/lingqu")
//    @RequiresPermissions("tWdkh:add")
    @ResponseBody
    public DataResult lingqu(@RequestBody TWdkhEntity tWdkh){
        return tWdkhService.lingqu(tWdkh);
    }
    @ApiOperation(value = "导入新增")
    @LogAnnotation(title = "我的客户", action = "导入新增")
    @PostMapping("tWdkh/upload")
    public DataResult upload(@RequestParam(value = "file") MultipartFile file) {
        //判断文件是否空
        if (file == null || file.getOriginalFilename() == null || "".equalsIgnoreCase(file.getOriginalFilename().trim())) {
            return DataResult.fail("文件为空");
        }
        String name = file.getOriginalFilename();
        String suffix = name.substring(name.lastIndexOf('.'));
        if(!suffix.equals(".xlsx")){
            return DataResult.fail("上传文件不是excel,正确文件后缀‘.xlsx’！");
        }
        return tWdkhService.saveFile(file);
    }
    @ApiOperation(value = "查询初始化选项")
    @LogAnnotation(title = "我的客户", action = "查询初始化选项")

    @GetMapping("tWdkh/infoData")
    @ResponseBody
    public DataResult infoData(){
        return tWdkhService.infoData();
    }
    @ApiOperation(value = "查询详情")
    @LogAnnotation(title = "我的客户", action = "查询详情")

    @PostMapping("tWdkh/infoDataById/{wdkhId}")
    @ResponseBody
    public DataResult getDataById(@PathVariable("wdkhId") String wdkhId) {
        return tWdkhService.getDataById(wdkhId);
    }

    @ApiOperation(value = "呼叫")
    @LogAnnotation(title = "我的客户", action = "呼叫")
    @PostMapping("tWdkh/outbound")
    @ResponseBody
    public DataResult outbound(@RequestBody TWdkhEntity tWdkh){
        return tWdkhService.outbound(tWdkh);
    }



}
